package com.glacier.yuyuan.gen.webapp.web;

import cn.hutool.core.date.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import java.beans.PropertyEditorSupport;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.Optional;

/**
 * date 2022-11-10 16:10
 * 基类 控制器
 *
 * @author glacier
 * @version 1.0
 */
@Controller
public class BaseController {

    protected final Logger LOGGER = LoggerFactory.getLogger(this.getClass());

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        //默认设置256，自定义设置为1024
        binder.setAutoGrowCollectionLimit(1024);
        binder.registerCustomEditor(LocalDateTime.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                setValue(DateUtil.parseLocalDateTime(text));
            }
        });

        binder.registerCustomEditor(LocalDate.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                setValue(Optional.ofNullable(DateUtil.parse(text))
                        .map(d -> LocalDate.ofInstant(d.toInstant(), ZoneId.systemDefault()))
                        .orElse(null));
            }
        });

        binder.registerCustomEditor(LocalTime.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                setValue(Optional.ofNullable(DateUtil.parse(text))
                        .map(d -> LocalTime.ofInstant(d.toInstant(), ZoneId.systemDefault()))
                        .orElse(null));
            }
        });
    }
}
